package com.lan.controller.sys;

import com.lan.entity.sys.User;
import com.lan.viewObject.SysR;
import com.lan.viewObject.SysResult;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("sys")
public class SysController {

    /**
     * default demo.
     *
     * */
    @GetMapping("demo")
    public String demo() {
        return "sys/index/demo";
    }

    /**
     * 登录界面
     *
     * */
    @GetMapping("login")
    public String login() {
        return "sys/login/loginPear";
    }

    /**
     * 登录
     *
     * */
    @ResponseBody
    @PostMapping("login")
    public Object login(final User param) {
        String account = param.getAccount();
        String password = param.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return SysResult.fail();
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return "未知账户";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return "密码不正确";
        } catch (LockedAccountException e) {
            e.printStackTrace();
            return "账户已锁定";
        } catch (ExcessiveAttemptsException e) {
            e.printStackTrace();
            return "用户名或密码错误次数过多";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return "用户名或密码不正确！";
        }
        if (subject.isAuthenticated()){
            return SysR.success("/pearIndex");
        } else {
            token.clear();
            return SysResult.fail("登录失败");
        }
    }

}
